<template>
    <el-upload ref='uploadRef' v-model:file-list="fileList" drag :auto-upload='true' :show-file-list="false"
        accept="image/*,video/*" :http-request="httpRequest" multiple>
        <el-icon class="el-icon--upload">
            <upload-filled />
        </el-icon>
        <div class="el-upload__text">
            拖动图片上传 或<em>点击上传</em>
        </div>
    </el-upload>
</template>
<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { storeToRefs } from 'pinia'
import http from '@/utils/axios.js'
import { createThumbnail, createImageUrl } from '@/utils/image.js'
import { compressImage } from '@/utils/compressor.js'
import { fileQueueHandle } from '@/utils/file-queue.js'
import FilesStore from '@/stores/files.js'
import { ElNotification } from 'element-plus'
const { addFile } = FilesStore()

const props = defineProps({
    dirId: {
        type: Number,
        default: 0
    },
    page: {
        type: Number,
        default: 1
    }
})
const dirId = computed(() => props.dirId)
const uploadRef = ref() //上传组件
const fileList = ref([])//上传图片列表

//文件上传成功回调
const handleSucces = function (data, uploadFile = null, uploadFiles = null) {
    if (data && data.id) {
        ElNotification.success({ message: data.title + '上传成功,5秒后生成地缩略图', duration: 1000 })
        setTimeout(() => {
            uploadRef.value!.clearFiles()
            data.url = createThumbnail(data)
            addFile(data, data.pid)
        }, 5000)
    }
}

//自定义文件上传行为
const httpRequest = async function (UploadRequestOptions) {
    const formData = new FormData()
    const pid = props.dirId;
    const page = props.page;
    formData.append('pid', pid)
    const file = UploadRequestOptions.file
    const fileName = file.name
    if (/^image/i.test(file.type)) {
        const result = await compressImage(file)
        formData.append('file', result, result.name);
    } else {
        formData.append('file', UploadRequestOptions.file)
    }
    const p = new Promise((resolve, reject) => {
        const item = {
            formData,
            fileName,
            isUpload: false,
            progress: ref(0),
            onUploadProgress: function (e) {
                item.progress.value = Math.floor(e.progress * 100)
            },
            success: function (res) {
                handleSucces(res)
                resolve(res)
            }
        }
        fileQueueHandle.addFile(item, pid, page)
    })
    return await p
}
</script>
<style scoped></style>